package cn.schoolwow.quickserver.request;

import java.io.IOException;
import java.io.InputStream;

public class ChunkedInputStream extends InputStream {
    private InputStream inputStream;
    private int pos = 0;
    private int chunkSize = -1;

    public ChunkedInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public int read() throws IOException {
        if (chunkSize == 0) {
            return -1;
        }
        if (pos < chunkSize) {
            pos++;
            return inputStream.read();
        } else if (pos == chunkSize) {
            if (0x0D != inputStream.read() || 0x0A != inputStream.read()) {
                throw new IOException("chunked块异常!");
            }
            pos = 0;
        }
        //读取chunk大小
        StringBuilder lengthBuilder = new StringBuilder();
        int b = inputStream.read();
        while (-1 != b && b != 0x0D) {
            lengthBuilder.append((char) b);
            b = inputStream.read();
        }
        if (b == -1 || 0x0A != inputStream.read()) {
            throw new IOException("chunked块异常!");
        }
        chunkSize = Integer.parseInt(lengthBuilder.toString(), 16);
        pos++;
        return inputStream.read();
    }
}
